package com.niuwa.p2p.service.impl.exchange;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.niuwa.p2p.core.utils.DictConstant;
import com.niuwa.p2p.core.utils.EmptyUtil;
import com.niuwa.p2p.dao.business.CustClaimDao;
import com.niuwa.p2p.dao.business.InvestProdRecordDao;
import com.niuwa.p2p.dao.claimtransfer.PlanTransferDao;
import com.niuwa.p2p.dao.claimtransfer.TransferApplyDao;
import com.niuwa.p2p.entity.business.InvestProdRecord;
import com.niuwa.p2p.entity.claimtransfer.PlanTransfer;
import com.niuwa.p2p.entity.claimtransfer.TransferApply;
import com.niuwa.p2p.service.exchange.IBatchClaimTransferService;
//import com.niuwa.p2p.service.exchange.IMatchService;
import com.niuwa.p2p.service.sequence.ISequenceService;
import com.niuwa.p2p.vo.business.CustClaimVo;

@Service
@Component("batchPlanClaimTransferJob")
public class BatchClaimTransferServiceImpl implements IBatchClaimTransferService {
	
	// TODO 交易相关review - 计划类债权转让，接口列表
	
	@Autowired
	private InvestProdRecordDao investProdRecordDao;
	@Autowired
	private CustClaimDao custClaimDao;
	@Autowired
	private PlanTransferDao planTransferDao;
	@Autowired
	private TransferApplyDao transferApplyDao;
//	@Autowired
//	private IMatchService matchService;
	@Autowired
	private ISequenceService sequenceService;
	
	
	private final Integer days = 3; // 提前 days天  开始批转让
	
	@Override
	public boolean batchPlanClaimTransfer() throws Exception {
		/**
		 * 生成转让申请记录；
		 * 锁定投资记录状态；
		 * 调接口:IMatchService.doLockFund()
		 * 
		 * 数据表:
		 * p2p_invest_prod_record,
		 * p2p_transfer_apply,p2p_plan_transfer,p2p_record_relative_apply
		 */
		//未来几天优选计划、债券认购列表
		List<InvestProdRecord> list = investProdRecordDao.selectListByDays(days);
		if(EmptyUtil.isNotEmpty(list)){
			// 锁定记录
			InvestProdRecord investProdRecord = null; 
			for(InvestProdRecord record : list){
				String recordNo = record.getRecordNo();
				// 获取version
				investProdRecord = investProdRecordDao.selectByPrimaryKey(record.getRecordNo());
				record.setCreditLock("Y");
				record.setVersion(investProdRecord.getVersion());
				List<CustClaimVo> claimList = custClaimDao.selectCustClaimInfoByRecordNo(record.getRecordNo());
				for(CustClaimVo vo : claimList){
					//生成转让记录
					TransferApply apply = new TransferApply();
					apply.setSerialNo(sequenceService.getCompleteSequenceBySeqKey("BHSQ"));//债权流水号
					apply.setProdCode(record.getProdCode());
					apply.setProdName(record.getProdName());
					apply.setYearRate(record.getYearRate());
					apply.setIsOwner("N");
					apply.setTransferRatio(new BigDecimal("0")); //转让系数
					apply.setTranferStatus(DictConstant.TranferStatus.WAIT_AUDIT.getCode()); //待审核
					apply.setTransferPrice(record.getInvestAmount()); // 转让价格
					apply.setTransferCapital(record.getInvestAmount()); // 转让债权本金
					apply.setRemainAmount(apply.getTransferCapital());
					apply.setClaimTo(DictConstant.ProjectTo.BACK.getName());
					apply.setNextRepayDate(vo.getNextRepayDate());
					apply.setRemainTerm(Integer.parseInt(vo.getRemainTerm()));
					apply.setRemainTermType(vo.getTimeType());
					apply.setCreditNo(vo.getCreditNo());
					apply.setProjectCode(vo.getProjectNo());
					apply.setProjectName(vo.getProjectName());
					apply.setExpireDate(vo.getExpireDate());
					apply.setAccruedInterest(new BigDecimal("0")); // 应计利息
					apply.setDiscount(new BigDecimal("0"));
					apply.setCreateTime(new Date());
					transferApplyDao.insertSelective(apply);
					//生成关联表p2p_record_relative_apply
					Map<String, Object> paramMap = new HashMap<String, Object>();
					paramMap.put("recordNo", recordNo);
					paramMap.put("serialNo", apply.getSerialNo());
					transferApplyDao.insertRecordRelativeApply(paramMap);
				}
				
				//投资计划转让表
				PlanTransfer planTransfer = new PlanTransfer();
				planTransfer.setRecordNo(recordNo);
				planTransfer.setStatus(DictConstant.TranferStatus.WAIT_AUDIT.getCode());//待审核
				planTransfer.setCreateTime(new Date());
				planTransfer.setCreditClaimCount(claimList.size());//该计划申请对应需要转让的债权数量
				try {
					investProdRecordDao.updateByPrimaryKeySelectiveByVersion(record);
					planTransferDao.insertSelective(planTransfer);
//					matchService.doLockFund(recordNo);
				} catch (Exception e) {
					e.printStackTrace();
				}
				
			}
			
			
		}
		
		return true;
	}

}
